<?php
	/**
	 * 登录
	 */
    class LoginIM extends APIBase {
		
		public $tag = "LoginIM";
		public $isLogin = false;
		
		
		public function before() {
			$this->initMysql();
			$this->initDataRedis();
			$this->initCacheRedis();
			$this->InitReportRedis();
			$this->inithttp();
			return true;
		}
	
		public function logic() {
            //接收token
		    if(!isset($this->param['token'])){
				$this->returnError(301,'登录错误,token不能为空!');
			}
			$this->i($this->param['token']);
			
            //接收uid
			if(!isset($this->param['uid'])){
				$this->returnError(301,'登录错误,uid不能为空!');
			}
			$this->i($this->param['uid']);
			
			
			$token = $this->param['token'];
			$uid = $this->param['uid'];
			//$this->i($token);
			//$this->i($uid);
			//判断token是否有效
			$isExistToken = $this->data_redis->exists("user_token:".$uid);
	        if($isExistToken){
				$Token = $this->data_redis->hMget("user_token:".$uid,array('token'));
				if($Token['token']!= $token){
					$this->returnError(303,'登录错误,token值有错!');
				}
			}else{
				$this->returnError(304,'登录token过期!');
			}

			//获取ip
            $ip = $this->getRealIp();

			//判断表中是否存在该用户
			$row = $this->mysql->select("player", "*", array('id' => $uid));
		    $c = count($row);
			
			//若不存在
			if($c==0){
				/*
			    $where_ip = array('register_ip' => trim($ip));
				$ipdata = $this->mysql->select("player", "COUNT(*) AS `count`", $where_ip);
				if ($ipdata[0]['count'] > 20) {	
					$this->returnError(304, '该设备已经超出可注册用户范围！');
				}
				$user_info = $this->AutoReg($passport,$nickname,$faceurl,$sex,$ip,$deviceID,$platform,$imei);
				$uid = $user_info['uid'];
				
				//注册数据上报
				$register_time = $this->data_redis->hGet("hu:{$uid}", 'create_time');
				$param = array('data'=>array(array(
				'user_id'=>(int)$uid,'cid'=>'10004','platform_type'=>'1','imei'=>$imei,'ua'=>'1',
				'register_time'=>$register_time,'channel'=>1,'agent'=>'','ip'=>"$ip"))); 
				Data_report('register',$param);
				
			    //把IM的accid,deviceID,sign
				$this->data_redis->hMset("hu:$uid",array('accid'=>$IM['accid'],'deviceID'=>$IM['deviceID'],'sign'=>$IM['sign']));
                //初始化匹配场战绩记录
				$this->data_redis->hMset("hu:$uid:match",array('user_id'=>$uid,'win_count'=>0,'lose_count'=>0,'winning_streak'=>0,'highest_winning_streak'=>0));
                $this->returnData($user_info);
                */
			}else{//玩家已经存在表中
			    //判断用户是否被禁用
			    if ($row[0]['status'] == 0) 
				{
					$this->returnError(310,"账号异常，请联系客服！");
				}
                
				$uid = $row[0]['id'];
				$this->initDataRedis($uid);
                
				
				
			    //判断redis是否存在玩家数据
				$isExists = $this->data_redis->exists("hu:{$uid}");
				$player = $this->data_redis->hMGet("hu:{$uid}", array('id','user','name'));
				if (!$isExists || $player['id']==null || $player['user'] == null) {
					//把玩家信息数据缓存到redis
					$this->data_redis->hMset("hu:{$uid}", $row[0]);
				}
				

				//判断玩家是否有背包数据
                $backpackCount = $this->cache_redis->keys("hbackpack:".$uid.":*"); 
                if(count($backpackCount)<=0){//如果玩家redis不存在背包 
					//判断数据库是否有玩家背包数据 
					$result = $this->mysql->find("select * from backpack where uid =".$uid);
					if(!empty($result)){//如果数据库存在背包,则把数据库背包数据写入redis 
						$r = array(); 
							foreach ($result as $key=>$val) { 
								$r = array(); 
								$r['uid'] = (int)$val['uid']; 
								$r['propid'] = (int)$val['propid'];
								$r['count'] = (int)$val['count'];
								$r['createtime'] = (int)$val['createtime'];
								$r['status'] =(int)$val['status'];
								$this->cache_redis->hMset("hbackpack:".$uid.":".$val['propid'],$r);
							}
					}else{
						$data = array('uid'=>$uid,'propid'=>1,'count'=>10,'createtime'=>time(),'status'=>1);
						$this->cache_redis->hMset("hbackpack:".$uid.":".'1',$data);
					
					}
				}
								
				//判断玩家是否有邮件数据
				$hemailbyuser = $this->cache_redis->keys("hemailbyuser:".$uid.":*");
			    if(count($hemailbyuser)<=0){//如果玩家redis不存在背包
			    //判断数据库是否有玩家背包数据
				    $result = $this->mysql->find("select * from emailbyuser where uid =".$uid);
				    if(!empty($result)){//如果数据库存在背包,则把数据库背包数据写入redis
				            foreach ($result as $key=>$val) {
		                        $r = array();
		                        $r['uid'] = (int)$val['uid'];
		                        $r['mid'] = (int)$val['mid'];
                                $r['is_read'] = (int)$val['is_read'];
                                $r['is_receive'] = (int)$val['is_receive'];
                                $r['send_date'] = (int)$val['send_date'];
                                $r['update_date'] = (int)$val['update_date'];	
                                $r['sender'] = (string)$val['sender'];									
		                        $this->cache_redis->hMset("hemailbyuser:".$uid.":".$val['id'],$r);
	                        }
			        }
			    }

				//判断玩家是否有匹配场战绩数据
				$isExists_match = $this->data_redis->exists("hu:".$uid.":match"); 
                if(!$isExists_match){
					$result = $this->mysql->find("select * from player_game where user_id=$uid");
					if(!empty($result)){//如果数据库存在匹配场数据,则写入redis 
						$r = array();
						foreach ($result as $key=>$val) {         
							$r['user_id'] = (int)$val['user_id']; 
							$r['win_count'] = (int)$val['win_count'];
							$r['lose_count'] = (int)$val['lose_count'];
							$r['winning_streak'] = (int)$val['winning_streak'];
							$r['highest_winning_streak'] = (int)$val['highest_winning_streak'];
						}
						$this->data_redis->hMset("hu:$uid:match",$r);
					}else{
						$this->data_redis->hMset("hu:$uid:match",array('user_id'=>$uid,'win_count'=>0,'lose_count'=>0,'winning_streak'=>0,'highest_winning_streak'=>0));
					}
                }
				
				//重置玩家session skey
				$salt = $this->data_redis->hGet("hu:{$uid}", 'salt');
				$now = time();
				$skey = md5($now . $salt);
				$this->data_redis->hMset("hu:$uid", array("update_time" => $now, "heartbeat_at" => $now, "skey" => $skey,"login_ip"=>$ip));
                $user_info = $this->data_redis->hMget("hu:$uid", array('point','user', 'name', 'sex','skey','login_days','password', 
					'is_get_login_reward','avater_url','is_vip','payment','imei','channel','platform_type','agent','device_num','accid','is_visitor'));
				
				
			    //登录数据上报
				$login_data =array('user_id'=>(int)$uid,'cid'=>Config::$info_report['cid'],'platform_type'=>$user_info['platform_type'],'imei'=>$user_info['imei'],'ua'=>$user_info['device_num'],
				'login_time'=>$now,'channel'=>$user_info['channel'],'agent'=>$user_info['agent'],'user_name'=>$user_info['name'],
				'user_level'=>1,'vip_level'=>1,'ip'=>"$ip");
				 $this->report_redis->rpush('login_data',json_encode($login_data));
			    
				//获取背包局数卡
				$round_card_num = $this->cache_redis->hGet("hbackpack:".$uid.":1",'count');

			    $user_info['name'] = (string)$user_info['name'];
				$user_info['accid'] = (int)$user_info['accid'];
			    $user_info['skey'] = (string)$user_info['skey'];
			    $user_info['uid'] = (int)$uid;
			    $user_info['password'] = (string)$user_info['password'];
			    $user_info['avater_url'] = (string)$user_info['avater_url'];
			    $user_info['is_vip'] = (int)$user_info['is_vip'];
				$user_info['sex'] = (int)$user_info['sex'];
			    $user_info['point'] = (int)$user_info['point'];
			    //$user_info["payment"] = (int)$user_info['payment'];
			    $user_info["round_card_num"] = (int)$round_card_num;
			    $user_info['ip'] = Config::$ip_server_confing['ip'];
			    $user_info['port'] = Config::$ip_server_confing['port'];
				$user_info['is_visitor'] = (int)$user_info['is_visitor'];
		        $this->returnData($user_info);
			}
	    }
	   
		private function AutoReg($passport,$nickname,$faceurl,$sex,$ip,$deviceID,$platform,$imei){
			$password = rand(1, 1000000);
			
			$new_user = $this->createUser($passport,$nickname,$faceurl,$sex,$ip,$password,$platform,$deviceID,$imei);

			$uid = $this->mysql->insert("player", $new_user);
			if($uid==0){
				$this->e("insert user error");
				$this->returnError(500, "server is error");
			}	
			$this->initDataRedis($uid);
			$new_user['id'] = $uid;
			
			//把用户数据缓存到redis
			$ret = $this->data_redis->hMset("hu:{$uid}", $new_user);
			if (!$ret) {
				$this->e("redis hMset error.");
				$this->returnError(3, "redis hMset error.");
			}
				
			$user_info = $this->data_redis->hMget("hu:$uid", array('id',
				'user', 'name', 'sex', 'skey','salt','login_days', 'is_get_login_reward', 
				'avater_url','is_vip','point','payment','round_card_num','passport'
			));
			
			$user_info['passport'] = (string)$user_info['passport'];
			$user_info['name'] = (string)$user_info['name'];
			$user_info['skey'] = (string)$user_info['skey'];
			$user_info['uid'] = (int)$uid;
			$user_info['sex'] = (int)$user_info['sex'];
			$user_info['password'] = (string)$password;
			$user_info['avater_url'] = (string)$user_info['avater_url'];
			$user_info['is_vip'] = (int)$user_info['is_vip'];
			$user_info['point'] = (int)$user_info['point'];
			$user_info["payment"] = (int)$user_info['payment'];
			$user_info["round_card_num"] = (int)$user_info['round_card_num'];
			$user_info['ip'] = Config::$ip_server_confing['ip'];
			$user_info['port'] = Config::$ip_server_confing['port'];
			return $user_info;
		}


		private function createUser($passport,$nickname,$faceurl,$sex,$ip,$password,$platform,$deviceID,$imei) {
			$now = time();
			$user_auto = $nickname;
			$password_auto = $password;
			$user_info = array();
			$user_info["passport"] = $passport;
			$user_info["user"] = $user_auto;
			$user_info["name"] = $user_auto; 
			$user_info["password"] = md5($password_auto . $password_auto);
			$user_info["salt"] = $password_auto;
			$user_info["status"] = 1; // 0：为封号的
			$user_info["platform_type"]=$platform;//0:安卓 1:IOS
			$user_info["sex"] = $sex;
			$user_info["skey"] = md5(time().$password_auto);//用户登录session
			$user_info["login_days"] = 0;//连续登录的天数
			$user_info["is_get_login_reward"] = 0;//领取连续登录奖励	
			$user_info["heartbeat_at"] = $now;//最后活动时间
			$user_info["create_time"] = $now;//注册时间
			$user_info["update_time"] = $now;//登录时间
			$user_info["avater_url"] = $faceurl;//头像
			$user_info["is_vip"] = 0;
			$user_info["register_ip"] = $ip;
			$user_info["login_ip"] = $ip;
            $user_info["device_num"] = $deviceID;
			$user_info["imei"] = $imei;
			$user_info['payment'] = 1;//支付方式(1  微信支付 2 支付宝支付)
			$user_info['point'] = 0;//玩家分数
			$user_info['round_card_num'] = 10;//局数卡
			return $user_info;
	    }
		   
		//私钥解密
		private function private_decrypt($input) {
			$private_key = file_get_contents(__dir__ .'/IMpay/private_key.txt');	
			openssl_private_decrypt(base64_decode($input),$output,$private_key);  
			return $output;  
		}  


    	public function after() {
    		$this->deinitDataRedis();
			$this->deinitCacheRedis();
			$this->deinitMysql();
			$this->deinithttp();
		}
    }
?>
